//
//  BaseCreatViewController.m
//  wulihan
//
//  Created by tang on 16/3/25.
//  Copyright © 2016年 tang. All rights reserved.
//

#import "BaseCreatViewController.h"
#import "Header.h"




#import "TitleTableView.h"
#import "LOadImageView.h"
//#import "BiliView.h"
#import "QiPaoView.h"
#import "ColorChangeView.h"
#import "LoadEditorImageView.h"
#import "ImageTextFieldView.h"
#import "HUDView.h"



#import "DataBaseSaveEditeImageModel.h"
#import "WuLiUpLoadImageRequest.h"



#import "ThreeViewController.h"
#import "CropperImageViewController.h"
#import "PostUpLoadImageViewController.h"



#define buttonPX            WithView/3.0
#define NOxuanzhongcolor      uicolor(21, 21, 21)

#define imageHeightPX           heightView-143-60
@interface BaseCreatViewController ()<TitleTableViewDelegate, QiPaoViewDelegate, UITextFieldDelegate, CropperImageViewControllerDelegate, LoadEditorImageViewDelegate, ColorChangeViewDelegate,ImageTextFieldViewDelegate>
{
//    NSMutableArray          *imageMutableArray;
//    NSMutableArray          *nameMutbleArray;


    UIButton                *biliButton;
    UIButton                *kuangButton;
    UIButton                *colorButton;

    UIButton                *cancleButton;

    CGPoint                 pointMake;
    NSMutableDictionary     *currentDic;
    NSMutableDictionary     *lastDic;

    NSMutableArray          *infoArray;


    int                     currentInt;
    int                     lastInt;

    float                   currentcontX;
    float                   currentcontY;
    CGFloat                 currentZoom;



    UIImage                 *sourceImage;

    LoadEditorImageView     *loadEditorView;
    QiPaoView               *qipaoView;
    ImageTextFieldView      *textView;
    HUDView                 *hudView;
   
}


@property (nonatomic, strong) TitleTableView *mainTableView;

//@property (nonatomic, strong) LOadImageView *loadImageView;
@property (nonatomic, strong) NSMutableArray *nameIndexArray;


@property (nonatomic, strong) ColorChangeView *changeColorView;


@end

@implementation BaseCreatViewController


sloganIntence(BaseCreatViewController);







- (void)loadView
{
    [super loadView];

    _nameIndexArray = [NSMutableArray new];
    
    currentDic = [NSMutableDictionary new];
    lastDic = [NSMutableDictionary new];
    
    infoArray = [NSMutableArray new];
    
    [self.view setBackgroundColor:uicolor(215, 215, 215)];
    
    
    currentInt = 0;

    
    _mainTableView = [[TitleTableView alloc] initWithFrame:CGRectMake(0, 0, WithView, 60)];
    //    [_mainTableView setBackgroundColor:[UIColor clearColor]];
    [_mainTableView setBackgroundColor:[UIColor whiteColor]];
    [_mainTableView setMTitleTableViewDelegate:self];
    [self.view addSubview:_mainTableView];
    
    
    loadEditorView = [[LoadEditorImageView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:loadEditorView];
    
    
    
    biliButton = [[UIButton alloc] initWithFrame:CGRectMake(0, heightView-46, buttonPX, 46)];
    [self.view addSubview:biliButton];
    
    kuangButton = [[UIButton alloc] initWithFrame:CGRectMake(buttonPX, heightView-46, buttonPX, 46)];
    [self.view addSubview:kuangButton];
    
    colorButton = [[UIButton alloc] initWithFrame:CGRectMake(2*buttonPX, heightView-46, buttonPX, 46)];
    [self.view addSubview:colorButton];
    
    
    _changeColorView = [[ColorChangeView alloc] initWithFrame:CGRectMake(0, heightView-46-93, WithView, 93.0)];
    [_changeColorView setBackgroundColor:uicolor(237, 237, 237)];
    [self.view addSubview:_changeColorView];
    [_changeColorView setHidden:YES];
    
    [self kkkkkkkk];
    
    NSLog(@"loadview");
    
    
    
    textView = [[ImageTextFieldView alloc] initWithFrame:CGRectMake(0, heightView - 48.0, WithView, 48.0)];
    
    [self.view addSubview:textView];
    [textView setHidden:YES];
}



- (void)kkkkkkkk
{
    [qipaoView removeFromSuperview];
    
    qipaoView = [[QiPaoView alloc] initWithFrame:CGRectMake(0, heightView-46-93, WithView, 93.0)];
    [qipaoView setBackgroundColor:uicolor(249, 249, 249)];
    [self.view addSubview:qipaoView];
    [qipaoView setMQiPaoViewDelegate:self];

}




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [textView setMImageTextFieldViewDelegate:self];
    
    
    [_changeColorView setHidden:YES];
    
    [loadEditorView setMLoadEditorImageViewDelegate:self];
    [_changeColorView setMColorChangeViewDelegate:self];
    
    
    [biliButton.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
    [biliButton setBackgroundColor:uicolor(249, 249, 249)];
    [biliButton setTitle:@"照片比例" forState:UIControlStateNormal];
    [biliButton setTitleColor:uicolor(117, 117, 117) forState:UIControlStateNormal];
    
    UIView *biliView = [[UIView alloc] initWithFrame:CGRectMake(biliButton.bounds.size.width - 0.5, 15, 1, 17)];
    [biliView setBackgroundColor:uicolor(205, 205, 205)];
    [biliButton addSubview:biliView];
    
    [kuangButton setSelected:YES];
    [kuangButton.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
    [kuangButton setBackgroundColor:uicolor(249, 249, 249)];
    [kuangButton setTitle:@"气泡" forState:UIControlStateNormal];
    [kuangButton setTitleColor:uicolor(117, 117, 117) forState:UIControlStateNormal];
    
    UIView *kuangView = [[UIView alloc] initWithFrame:CGRectMake(kuangButton.bounds.size.width - 1, 15, 1, 17)];
    [kuangView setBackgroundColor:uicolor(205, 205, 205)];
    [kuangButton addSubview:kuangView];
    
    [colorButton.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
    [colorButton setBackgroundColor:uicolor(249, 249, 249)];
    [colorButton setTitle:@"文本样式" forState:UIControlStateNormal];
    [colorButton setTitleColor:uicolor(117, 117, 117) forState:UIControlStateNormal];
    [colorButton setSelected:NO];
    
    [biliButton setTag:1];
    [kuangButton setTag:2];
    [colorButton setTag:3];
    
    
    [biliButton addTarget:self action:@selector(changeEdite:) forControlEvents:UIControlEventTouchUpInside];
    [kuangButton addTarget:self action:@selector(changeEdite:) forControlEvents:UIControlEventTouchUpInside];
    [colorButton addTarget:self action:@selector(changeEdite:) forControlEvents:UIControlEventTouchUpInside];
    [cancleButton addTarget:self action:@selector(removeKeyBoard) forControlEvents:UIControlEventTouchUpInside];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addsver:) name:@"addnewimage" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyBoard:) name:@"chuxianjianpan" object:nil];
    
    
//读取第一张图盘
    
//    NSLog(@"viewload");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self readDataBaseImage:0];
    lastInt = 0;
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self kkkkkkkk];
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    //键盘高度
    CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [textView setFrame:CGRectMake(0, heightView-keyBoardFrame.size.height-48, WithView, 48.0)];
}


- (void)keyboardWillBeHidden:(NSNotification *)notion
{
    [textView setHidden:YES];
    [textView setFrame:CGRectZero];
}




- (void)addsver:(NSNotification *)notion
{
    [infoArray removeAllObjects];
    [infoArray addObjectsFromArray:[notion object]];
}



- (void)popToView
{
    [self.navigationController popViewControllerAnimated:YES];
//    [_MBaseDataSource getImageArray:infoArray];
}




/*读取数据库中对应的照片，编辑照片对应的位置和数据，并获得现在的zhaopian */
- (void)chooseCurrentWithName:(NSString *)currentName lastWithName:(NSString *)lastName
{
//    NSLog(@"%@", currentName);
    currentInt = [[_nameIndexArray objectAtIndex:[currentName intValue]] intValue];
    
    NSString *currentIndex = [NSString stringWithFormat:@"%d", currentInt];
//    NSLog(@"%@", currentIndex);
    
    [[DataBaseSaveEditeImageModel sharedInstance] rearDataBaseImageWithName:currentIndex andWriteIMageWithlast:lastName getImage:^(NSData *data, NSData *cropData, NSDictionary *qipaoDic){
        
        
        sourceImage = [UIImage imageWithData:data];
//
        if (WithView != 320 && WithView != 375)
        {
            [loadEditorView setFrame:CGRectMake(0, 60, [UIImage imageWithData:cropData].size.width/3.0, [UIImage imageWithData:cropData].size.height/3.0)];
        }
        else
        {
            [loadEditorView setFrame:CGRectMake(0, 60, [UIImage imageWithData:cropData].size.width/2.0, [UIImage imageWithData:cropData].size.height/2.0)];
        }

        [loadEditorView loadImage:[UIImage imageWithData:cropData]];
        [loadEditorView removeQipaoFromView];
        
        dispatch_async(dispatch_get_main_queue(), ^{
        
            [loadEditorView loadQipao:qipaoDic];
        });
        
    }];
    
}



//读取数据库照片
- (void)readDataBaseImage:(int)curr
{
    
//    NSLog(@"11111");
    
    NSMutableArray *mutableArray = [NSMutableArray new];
    [_nameIndexArray removeAllObjects];
    
    [[DataBaseSaveEditeImageModel sharedInstance] readYaSuoImage:^(NSData *yasuoImageData, NSString *nameString){
    
//        NSLog(@"%@", nameString);
        [_nameIndexArray addObject:nameString];
        UIImage *image = [UIImage imageWithData:yasuoImageData];
        [mutableArray addObject:image];
    }];
    
    //将图片传给所列表,选中第一个
    [_mainTableView setDataArray:mutableArray];
    [_mainTableView setSelectInt:curr];
    currentInt = [[_nameIndexArray objectAtIndex:0] intValue];
    [[DataBaseSaveEditeImageModel sharedInstance] rearDataBaseImageWithName:[NSString stringWithFormat:@"%d", currentInt] andWriteIMageWithlast:@"0" getImage:^(NSData *data, NSData *cropData, NSDictionary *qipaoDic){
        
        sourceImage = [UIImage imageWithData:data];
        [loadEditorView setBackgroundColor:[UIColor redColor]];
        if (WithView != 320 && WithView != 375)
        {
            [loadEditorView setFrame:CGRectMake(0, 60, [UIImage imageWithData:cropData].size.width/3.0, [UIImage imageWithData:cropData].size.height/3.0)];
        }
        else
        {
            [loadEditorView setFrame:CGRectMake(0, 60, [UIImage imageWithData:cropData].size.width/2.0, [UIImage imageWithData:cropData].size.height/2.0)];
        }
        
        [loadEditorView loadImage:[UIImage imageWithData:cropData]];
        
//        dispatch_async(dispatch_get_main_queue(), ^{
        
        [loadEditorView removeQipaoFromView];
        [loadEditorView loadQipao:qipaoDic];

    }];
    

    
}



//添加照片
- (void)tianjiaImage
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        ThreeViewController *view = [ThreeViewController new];
//        view.imageArray = _arrayWithArray;
//        view.nameArray = _nameIndexArray;
        view.plusImage = YES;
        
        [self presentViewController:view animated:YES completion:nil];
    });
}








- (void)buttonReload
{
    [_changeColorView   setHidden:YES];
}


//编辑照片
- (void)changeEdite:(UIButton *)sender
{
//    [self buttonReload];
    if (sender.tag == 1)
    {
        CropperImageViewController *cropView = [[CropperImageViewController alloc] init];
        cropView.sourceImage = sourceImage;
        [cropView setMCropperImageViewControllerDelegate:self];
        [self presentViewController:cropView animated:YES completion:nil];
        
        [biliButton setTitleColor:uicolor(36, 36, 36) forState:UIControlStateNormal];
        [kuangButton setTitleColor:uicolor(117, 117, 117) forState:UIControlStateNormal];
        [colorButton setTitleColor:uicolor(117, 117, 117) forState:UIControlStateNormal];
    }
    else if (sender.tag == 2)
    {
//        [kuangButton        setBackgroundColor:uicolor(35, 35, 35)];
//        [_qipaoView         setHidden:NO];
        if ([kuangButton isSelected]) {
            
            [kuangButton setSelected:NO];
            [qipaoView setHidden:YES];
        }
        else
        {
            [kuangButton setSelected:YES];
            [qipaoView setHidden:NO];

        }
        [kuangButton setTitleColor:uicolor(36, 36, 36) forState:UIControlStateNormal];
        [biliButton setTitleColor:uicolor(117, 117, 117) forState:UIControlStateNormal];
        [colorButton setTitleColor:uicolor(117, 117, 117) forState:UIControlStateNormal];

    }
    else if (sender.tag == 3)
    {
        [kuangButton setSelected:NO];
        [qipaoView setHidden:YES];
        
        if ([colorButton isSelected]) {
            
            [colorButton setSelected:NO];
            [_changeColorView setHidden:YES];
        }
        else
        {
            [colorButton setSelected:YES];
            [_changeColorView setHidden:NO];
            
        }

        [kuangButton setTitleColor:uicolor(117, 117, 117) forState:UIControlStateNormal];
        [biliButton setTitleColor:uicolor(117, 117, 117) forState:UIControlStateNormal];
        [colorButton setTitleColor:uicolor(36, 36, 36) forState:UIControlStateNormal];

    }
}



- (void)croperWithImage:(UIImage *)image withRect:(CGRect)rectSize
{
    [[DataBaseSaveEditeImageModel sharedInstance] writeCropeImage:UIImagePNGRepresentation(image) witnName:[NSString stringWithFormat:@"%d", currentInt]];
    NSLog(@"%f------%f", rectSize.size.width, image.size.height);
    
    [loadEditorView loadImage:image];
    [loadEditorView setFrame:CGRectMake(0, 60, image.size.width/2.0, image.size.height/2.0)];

}




#pragma mark----改变气泡透明度
- (void)changeAlpha:(float)alpha
{
    NSLog(@"%f", alpha);
//    [loadEditorView loadDataBaseQipao:<#(NSDictionary *)#>]
    [loadEditorView setAlpha:alpha];
}

- (void)changeTextColor:(NSString *)colorString
{
    [loadEditorView setColorTextString:colorString];
}

#pragma mark---完成并截图
- (void)wanchengBuoont
{
//    NSLog(@"%@", _nameIndexArray);
    
    
//    hudView = [[HUDView alloc] initWithFrame:CGRectMake((CGFloat) ((self.view.frame.size.width - 55) * 0.5),
//                                                        (CGFloat) ((self.view.frame.size.height - 20) * 0.5), 55, 20)];
//    [self.view addSubview:hudView];
//    
//    [hudView showAnimated:YES];

    
    NSMutableArray *array = [NSMutableArray new];
    NSMutableArray *sourceArray = [NSMutableArray new];
    NSMutableArray *connectArray = [NSMutableArray new];
    
    for (NSString *string in _nameIndexArray)
    {
//        NSLog(@"%@", string);
        //读取数据库中截取照片
        [[DataBaseSaveEditeImageModel sharedInstance] readUpLoadImageWithName:string withCallBack:^(NSData *data, NSData *sourceData, NSString *imageConnectID){
        
//            NSLog(@"%@", imageConnectID);
            [connectArray addObject:imageConnectID];
            [array addObject:data];
            [sourceArray addObject:sourceData];
        }];
    }
    
//    NSLog(@"%@", [UIImage imageWithData:array[0]]);
//    PostUpLoadImageViewController *postView = [[PostUpLoadImageViewController alloc] init];
//    postView.imageArray = array;
//    postView.sourceArray = sourceArray;
//    postView.connectIDArray = connectArray;
//    [self.navigationController pushViewController:postView animated:YES];

//    [hudView removeFromSuperview];
}



- (UIImage *)imageFromView:(UIView *)theView atFrame:(CGRect)r
{
    UIGraphicsBeginImageContextWithOptions(theView.frame.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    UIRectClip(r);
    [theView.layer renderInContext:context];
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return  theImage;
}

#pragma mark-----获取气泡
- (void)getQipaoImageNameInfo:(NSDictionary *)infoDic
{
    lastInt = 1;
    [loadEditorView removeQipaoFromView];
    [loadEditorView loadQipao:infoDic];
}


#pragma mark-----保存记录  loadimage代理
- (void)saveImage:(UIImage *)image WithqipaoDic:(NSDictionary *)dic
{
//    NSLog(@"%@", [NSString stringWithFormat:@"%d", currentInt]);
//    NSLog(@"222222222222");

    if (lastInt == 0)
    {
        lastInt =1;
    }
    else
    {
//        dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
            [[DataBaseSaveEditeImageModel sharedInstance] writeCropIMage:UIImagePNGRepresentation(image) withQipaoInfo:dic witnName:[NSString stringWithFormat:@"%d", currentInt]];

//        });
        
    }
//
}






#pragma mark-----弹出键盘
- (void)showKeyBoard:(NSNotification *)notion
{
    [cancleButton setHidden:NO];
    [textView.textfiled becomeFirstResponder];
    [textView setHidden:NO];
}

- (void)changeText:(NSString *)contentString
{
    [loadEditorView setContentString:contentString];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [cancleButton setHidden:YES];
    [textView.textfiled resignFirstResponder];
    return YES;
}


- (void)removeKeyBoard
{
    [cancleButton setHidden:YES];
    [textView.textfiled resignFirstResponder];
    [loadEditorView cropIMage];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
